package org.example.io.handler;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.example.io.protocol.Attributes;
import org.example.io.protocol.packet.MessageRequestPacket;
import org.example.io.protocol.packet.MessageResponsePacket;
import org.example.io.session.ServerSession;
import org.example.io.session.SessionUtil;
import org.example.io.util.LoginUtil;

@Slf4j
public class MessageRequestPacketHandler extends SimpleChannelInboundHandler<MessageRequestPacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageRequestPacket msg) throws Exception {
        log.info("服务端收到消息：{}", msg.getMessage());

        String toUsername = msg.getToUsername();
        Channel channel = SessionUtil.getChannel(toUsername);
        if (LoginUtil.hasLogin(channel)) {
            ServerSession channelSession = SessionUtil.getSession(channel);
            MessageResponsePacket resPacket = new MessageResponsePacket();
            resPacket.setFromUsername(SessionUtil.getSession(ctx.channel()).getUserName());
            resPacket.setMessage(msg.getMessage());
            resPacket.setSuccess(true);
            channel.writeAndFlush(resPacket);
        }
    }
}
